package org.hako.recite.word.tool;

/**
 * Detect yomi of single kannji
 * 
 * @since 0.4.14
 * @author <a href="mailto:xnnyygn@gmail.com">xnnyygn</a>
 */
public class SingleKannjiDetector implements KannjiYomiDetector {

	@Override
	public boolean check(String rawKannji, String rawYomi,
			KannjiExtractResult extractResult) {
		return extractResult.getCount() == 1;
	}

	@Override
	public KannjiYomiDetectResult detect(String rawKannji, String rawYomi,
			KannjiExtractResult extractResult) {
		return detect(rawKannji, rawYomi, extractResult.get(0));
	}

	/**
	 * Detect yomi of kannji.
	 * 
	 * @param rawKannji
	 * @param rawYomi
	 * @param kannjiIndex
	 * @return
	 */
	public KannjiYomiDetectResult detect(String rawKannji, String rawYomi,
			int kannjiIndex) {
		String kannji = rawKannji.substring(kannjiIndex, kannjiIndex + 1);
		String yomi = rawYomi.substring(kannjiIndex, rawYomi.length()
				- (rawKannji.length() - 1 - kannjiIndex));
		String kannjiWithYomi = generateKannjiWithYomi(rawKannji, kannjiIndex,
				yomi);
		return new KannjiYomiDetectResult(new KannjiYomiPair(kannji, yomi),
				kannjiWithYomi);
	}

	/**
	 * Generate string contains kannji and yomi.
	 * 
	 * @param rawKannji
	 * @param kannjiIndex
	 * @param yomi
	 * @return
	 */
	private String generateKannjiWithYomi(String rawKannji, int kannjiIndex,
			String yomi) {
		StringBuilder builder = new StringBuilder();
		builder.append(rawKannji.subSequence(0, kannjiIndex + 1));
		builder.append('(');
		builder.append(yomi);
		builder.append(')');
		builder.append(rawKannji.substring(kannjiIndex + 1));
		return builder.toString();
	}

}
